package cc.risingsun.wing.dai;

import java.io.InputStream;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.cfg.C3P0Config;
import com.mchange.v2.c3p0.cfg.C3P0ConfigFinder;
import com.mchange.v2.c3p0.cfg.C3P0ConfigXmlUtils;

/**
 * 
 * @author iron.yin@gmail.com
 * @since 2012-8-14
 */
public class C3P0DataSourceFactory implements IDataSourceFactory {

	static {
		System.setProperty(C3P0Config.CFG_FINDER_CLASSNAME_KEY, WingC3P0ConfigFinder.class.getName());
	}

	public static class WingC3P0ConfigFinder implements C3P0ConfigFinder {

		@Override
		public C3P0Config findConfig() throws Exception {
			C3P0Config out;
			InputStream is = getClass().getResourceAsStream("config/c3p0-config.xml");
			try {
				C3P0Config xmlConfig = C3P0ConfigXmlUtils.extractXmlConfigFromInputStream(is);
				out = xmlConfig;
			} finally {
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return out;
		}
	}

	private final ComboPooledDataSource datasource = new ComboPooledDataSource("mysql");

	public DataSource getDataSource() {
		return datasource;
	}

}
